import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput, ScrollView,
	PixelRatio
} from 'react-native';
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { enterpriseStyles } from '../../../enterprise/_common/enterpriseStyle';
import { InputRow, LargeBtn } from '../../../requirement-plan/component/Component.js';
import ModalAreaComponent from '../../../../component/ModalAreaComponent.js';
import ToastUtil from '../../../../utils/toast';
import HTTP from '../../../../utils/http'
import Dictionary from '../../../../utils/dictionary';
import { RadoiCpt } from '../../../offer/create/_components/form/RadoiCpt';
const scale = GLOBAL.SCALE;

const arrowLeft = require('../../../../imgs/sanjiao3.png');
export class AddAddressPage extends Component {

	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '地址信息',
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		};
	};

	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		this.addressData = {
			companyId: params.companyId
		};  //参数
		this.state = {
			addressTypeList: [], // 地址类型
			addressType: '', // 默认选择库区
			modalAreaVisible: false,  // 显示隐藏
			areaText: '请选择地址',
			edit: params.edit || false,
			areaModalProp: {
				cancelPress: () => {
					this.setState({
						modalAreaVisible: false
					});
				},
				confirmPress: (data) => {
					this.setState({
						modalAreaVisible: false
					});
				},
			},
		}
		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);
	}


	async componentWillMount() {
		await this.getDictionary();
		this._getPropsInfo();
		this._getAddressInfo();
	}

	async getDictionary() {
		let addressTypeList = await Dictionary.get('EC_ADDRESS_TYPE');
		if (addressTypeList && addressTypeList.length > 0) {
			addressTypeList.map(item => {
				item.title = item.dictName
			})
			this.setState({
				addressTypeList,
				addressType: addressTypeList[0].dictKey,
			}, () => {
				this.addressData.addressType = addressTypeList[0].dictKey;
			})
		}
	}

	_getPropsInfo() {
		let { item } = this.props.navigation.state.params
		if (item) {
			this.addressData = item
			// this.addressData.contactorName = item.contactorName
			// this.addressData.mobileNo = item.mobileNo
			// this.addressData.addressName = item.addressName
			// this.addressData.provinceCode = item.fullName
			// this.addressData.detailAddress = item.detailAddress
			// this.addressData.addressName = item.addressName
			this.setState({
				addressType: item.addressType,
				areaText: item.fullName || '请选择地址'
			})
		}
	}
	//获取-交货地址数据
	async _getAddressInfo() {
		this.setState({
			loaded: true
		});
		let mapData = require('../../../../data/map.json');
		this.setState({
			areaModalProp: {
				addressInfo: mapData.data,
				cancelPress: () => {
					this.setState({
						modalAreaVisible: false
					});
				},
				confirmPress: (data) => {
					const { province, city, area } = data;
					const areaText = `${province.areaName}${city.areaName ? ('，' + city.areaName) : ''}${area.areaName ? ('，' + area.areaName) : ''}`;
					this.addressData.provinceCode = province.areaId || '';
					this.addressData.cityCode = city.areaId || '';
					this.addressData.areaCode = area.areaId || '';
					this.setState({
						modalAreaVisible: false,
						areaText
					});
				},
			},
			loaded: false
		})
	}

	// 点击地址 地址弹框显示隐藏
	_isShow = () => {
		if (this.state.edit) {
			return
		}
		this.setState({
			modalAreaVisible: !this.state.modalAreaVisible
		});
	}

	/**
 * 点击底部按钮
 */
	async _didPressLargeBtn() {
		if (!this.addressData.contactorName) {
			ToastUtil.showWarning('请选择联系人');
			return;
		}
		if (!this.addressData.mobileNo) {
			ToastUtil.showWarning('请输入电话');
			return;
		}
		if (!this.state.edit && this.addressData.addressType == '1') {
			if (!this.addressData.addressName) {
				ToastUtil.showWarning('请输入仓库名称');
				return;
			}
			if (!this.addressData.provinceCode) {
				ToastUtil.showWarning('请选择地区');
				return;
			}
			if (!this.addressData.detailAddress) {
				ToastUtil.showWarning('请填写详细地址');
				return;
			}
		} else if (!this.state.edit && this.addressData.addressType == '2') {
			if (!this.addressData.provinceCode) {
				ToastUtil.showWarning('请选择地区');
				return;
			}
			if (!this.addressData.addressName) {
				ToastUtil.showWarning('请输入片区名称');
				return;
			}
		}
		let sendData = {
			bizType: 'COMPANY_ADDRESS_INFO',
			addressList: [this.addressData]
		}
		this.addressInfo = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), sendData);
		if (this.addressInfo) {
			ToastUtil.showSuccess(`地址${this.state.edit ? '修改' : '新增'}成功`);
			setTimeout(() => {
				this.props.navigation.state.params.refeshBack();
				this.props.navigation.navigate('DeliveryAddress');
			}, 1000)
		}
	}

	changeAddressType = (res) => {
		if (res) {
			console.debug(res)
			this.setState({
				addressType: res.addressType,
			}, () => {
				this.addressData.addressType = res.addressType
			})
		}
	}


	render() {
		const { contactorName, mobileNo, detailAddress, addressName } = this.addressData;
		const { areaText, modalAreaVisible, areaModalProp, addressTypeList, addressType, edit } = this.state;
		return (
			<View style={[styles.container]}>
				<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} >
					<View style={styles.wrap}>
						<View style={{ width: 345 * scale, marginTop: 20 * scale }}>
							<View style={edit ? { opacity: 0.6 } : null}>
								<RadoiCpt data={{
									id: 'addressType',
									selectKey: addressType,
									title: '地址类型',
									listData: addressTypeList,
									readOnly: edit
								}}
									callBack={this.changeAddressType}
								/>
							</View>

							<View style={styles.field}>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
									<Text style={styles.lableText}>联系人</Text>
									<TextInput
										ref="bonusInput"
										style={styles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入联系人"}
										placeholderTextColor="#404040"
										maxLength={100}
										editable={true}
										defaultValue={contactorName}
										onChangeText={(contactorName) => {
											this.addressData.contactorName = contactorName;
										}}
									/>
								</View>
							</View>
							<View style={styles.field}>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
									<Text style={styles.lableText}>电话</Text>
									<TextInput
										ref="mobileNoInput"
										keyboardType="numeric"
										style={styles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入联系电话"}
										placeholderTextColor="#404040"
										editable={true}
										defaultValue={mobileNo}
										onChangeText={(mobileNo) => {
											this.addressData.mobileNo = mobileNo;
										}}
									/>
								</View>
							</View>
							<View style={edit ? { opacity: 0.6 } : null}>
								<TouchableOpacity style={styles.field}
									onPress={() => this._isShow()}
									disabled={edit}
								>
									<Text style={styles.fieldcolor}>*</Text>
									<View style={styles.fieldRight}>
										<Text style={styles.lableText}>所在地区</Text>
										<View style={styles.textInputAddress}>
											<Text style={{
												fontSize: 13 * scale,
												color: '#404040',
												paddingLeft: 5 * scale,
												flex: 1
											}} numberOfLines={1}>{areaText}</Text>
											<View style={styles.textInputIcon} >
												<Image source={arrowLeft} style={styles.arrowLeft} />
											</View>
										</View>
									</View>
								</TouchableOpacity>
								{
									addressType == '1' ?
										(<View style={styles.field}>
											<Text style={styles.fieldcolor}>*</Text>
											<View style={styles.fieldRight}>
												<Text style={styles.lableText}>详细地址</Text>
												<TextInput
													ref="bonusInput"
													style={styles.textInput}
													underlineColorAndroid='transparent'
													placeholder={"请输入详细地址"}
													placeholderTextColor="#404040"
													maxLength={500}
													editable={!edit}
													defaultValue={detailAddress}
													onChangeText={(detailAddress) => {
														detailAddress = detailAddress.replace(/ /g, '');
														this.addressData.detailAddress = detailAddress;
													}}
												/>
											</View>
										</View>) : null
								}
								<View style={styles.field}>
									<Text style={styles.fieldcolor}>*</Text>
									<View style={styles.fieldRight}>
										<Text style={styles.lableText}>{addressType == '1' ? '仓库名称' : '片区名称'}</Text>
										<TextInput
											ref="addressName"
											style={styles.textInput}
											underlineColorAndroid='transparent'
											placeholder={addressType == '1' ? '请输入仓库名称' : '请输入片区名称'}
											placeholderTextColor="#404040"
											maxLength={30}
											editable={!edit}
											defaultValue={addressName}
											onChangeText={(addressName) => {
												this.addressData.addressName = addressName;
											}}
										/>
									</View>
								</View>
							</View>
						</View>
					</View>
				</ScrollView >
				<View style={{ flexDirection: 'row', justifyContent: 'center' }}>
					<TouchableOpacity style={styles.button} onPress={() => this._didPressLargeBtn()}>
						<Text style={styles.buttonText}>保存</Text>
					</TouchableOpacity>
				</View>
				{areaModalProp.addressInfo ? <ModalAreaComponent {...areaModalProp} selectCustom={true} visible={modalAreaVisible} /> : null}
			</View>

		)
	}
}

const styles = StyleSheet.create({
	scrollView: {
		flex: 1,
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	wrap: {
		backgroundColor: '#fff',
		alignItems: 'center',
	},
	button: {
		marginTop: 20 * scale,
		marginBottom: 50 * scale,
		width: 99 * scale,
		height: 39 * scale,
		backgroundColor: '#0E7FFD',
		borderRadius: 15 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	buttonText: {
		fontSize: 14 * scale,
		color: '#fff'
	},
	field: {
		flexDirection: 'row',
		marginBottom: 12 * scale,
		paddingTop: 10 * scale,
	},
	fieldRight: {
		borderBottomColor: '#000',
		borderBottomWidth: 1,
		paddingBottom: 10 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		flex: 1,
	},
	fieldcolor: {
		color: 'red',
		marginRight: 5 * scale,
		width: 8 * scale
	},
	lableText: {
		fontWeight: '600',
		fontSize: 14 * scale,
		color: '#000',
		width: 80 * scale,
	},
	textInput: {
		borderWidth: 0,
		fontSize: 13 * scale,
		width: '100%',
		padding: 0,
		alignSelf: 'center',
	},
	textInputAddress: {
		alignItems: 'center',
		flex: 1,
		justifyContent: 'space-between',
		flexDirection: 'row',
		flexWrap: 'wrap'
	},
	textInputIcon: {
		alignItems: 'center',
		justifyContent: 'flex-end',
		flexDirection: 'row',
		// height: 22 * scale,
		width: 52 * scale,
		paddingRight: 10 * scale
	},
	arrowLeft: {
		width: 10 * scale,
		height: 15 * scale,
	},
})